type EventHandlers<E> = {
	[K in keyof E]: Array<(payload: E[K]) => void>;
};

class EventBus<E> {
	private handlers: EventHandlers<E> = {} as EventHandlers<E>

	// 订阅事件
	on<K extends keyof E>(eventName: K, handler: (payload: E[K]) => void): EventBus<E> {
		if (!this.handlers[eventName]) {
			this.handlers[eventName] = []
		}
		this.handlers[eventName].push(handler)
		return this
	}

	// 发布事件
	emit<K extends keyof E>(eventName: K, payload: E[K]): void {
		const eventHandlers = this.handlers[eventName]
		if (eventHandlers) {
			eventHandlers.forEach((handler) => handler(payload))
		}
	}

	// 取消订阅事件
	off<K extends keyof E>(eventName: K, handler: (payload: E[K]) => void): void {
		const eventHandlers = this.handlers[eventName]
		if (eventHandlers) {
			const index = eventHandlers.indexOf(handler)
			if (index !== -1) {
				eventHandlers.splice(index, 1)
			}
		}
	}
}

export default EventBus